package cn.sfrog.project.biz.admin.service.impl;

import cn.sfrog.common.constant.Constants;
import cn.sfrog.common.core.domain.entity.SysUser;
import cn.sfrog.common.core.domain.model.LoginUser;
import cn.sfrog.common.core.redis.RedisCache;
import cn.sfrog.common.exception.ApiException;
import cn.sfrog.common.utils.SecurityUtils;
import cn.sfrog.common.utils.ServletUtils;
import cn.sfrog.common.utils.StringUtils;
import cn.sfrog.common.utils.ip.IpUtils;
import cn.sfrog.project.biz.admin.domain.BizUserEnsureMoney;
import cn.sfrog.project.biz.admin.domain.BizUserRecharge;
import cn.sfrog.project.biz.admin.domain.BizUserRechargePayment;
import cn.sfrog.project.biz.admin.domain.vo.BizUserRechargeFormVO;
import cn.sfrog.project.biz.admin.domain.vo.BizUserRechargeQueryVO;
import cn.sfrog.project.biz.admin.domain.vo.BizUserRechargeVO;
import cn.sfrog.project.biz.admin.enums.PayMethodEnum;
import cn.sfrog.project.biz.admin.mapper.BizUserRechargeMapper;
import cn.sfrog.project.biz.admin.pay.PayFactory;
import cn.sfrog.project.biz.admin.service.IBizServiceOrderService;
import cn.sfrog.project.biz.admin.service.IBizUserRechargePaymentService;
import cn.sfrog.project.biz.admin.service.IBizUserRechargeService;
import cn.sfrog.project.biz.applet.config.PayUtil;
import cn.sfrog.project.biz.applet.config.WxApiType;
import cn.sfrog.project.biz.applet.config.WxNotifyType;
import cn.sfrog.project.biz.applet.config.WxPayConfig;
import cn.sfrog.project.biz.applet.utils.WechatUtil;
import cn.sfrog.project.biz.web.vo.account.AppPaymentQueryPayStatusVO;
import cn.sfrog.project.biz.web.vo.account.AppPaymentStatusVO;
import cn.sfrog.project.biz.web.vo.account.AppUserRechargeFormVO;
import cn.sfrog.project.biz.web.vo.order.AppServiceOrderVO;
import cn.sfrog.system.domain.vo.BizStatusChangeVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.jpay.ext.kit.PaymentKit;
import com.jpay.weixin.api.WxPayApi;
import com.jpay.weixin.api.WxPayApiConfig;
import com.jpay.weixin.api.WxPayApiConfigKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



@Service
@Slf4j
public class BizUserRechargeServiceImpl extends ServiceImpl<BizUserRechargeMapper, BizUserRecharge> implements IBizUserRechargeService {

    @Autowired
    private CloseableHttpClient wxPayClient;
    @Autowired
    private WxPayConfig wxPayConfig;
    @Resource
    private BizUserRechargeMapper bizUserRechargeMapper;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IBizUserRechargePaymentService bizUserRechargePaymentService;

    @Autowired
    private IBizServiceOrderService bizServiceOrderService;
    @Value("${wxPay.appId}")
    private String appId;

    @Value("${wxPay.mchId}")
    private String mchId;
    @Value("${wxPay.secret}")
    private String secret;

    @Value("${wxPay.notifyUrl}")
    private String notifyUrl;

    /**
     * 查询用户充值
     *
     * @param id 用户充值主键
     * @return 用户充值
     */
    @Override
    public BizUserRechargeVO selectBizUserRechargeById(Long id) {
        return bizUserRechargeMapper.selectBizUserRechargeById(id);
    }

    /**
     * 查询用户充值列表
     *
     * @param query 用户充值
     * @return 用户充值
     */
    @Override
    public List<BizUserRechargeVO> selectBizUserRechargeList(BizUserRechargeQueryVO query) {
        return bizUserRechargeMapper.selectBizUserRechargeList(query);
    }

    /**
     * 新增用户充值
     *
     * @param form 用户充值
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean insertBizUserRecharge(BizUserRechargeFormVO form) {
        BizUserRecharge bizUserRecharge = new BizUserRecharge();
        BeanUtils.copyProperties(form, bizUserRecharge);
        bizUserRecharge.setCreateTime(new Date());
        bizUserRecharge.setCreateBy(SecurityUtils.getUsername());
        bizUserRecharge.setUpdateTime(new Date());
        bizUserRecharge.setUpdateBy(SecurityUtils.getUsername());
        return bizUserRecharge.insert();
    }

    /**
     * 修改用户充值
     *
     * @param form 用户充值
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean updateBizUserRecharge(BizUserRechargeFormVO form) {
        BizUserRecharge bizUserRecharge = new BizUserRecharge();
        BeanUtils.copyProperties(form, bizUserRecharge);
        bizUserRecharge.setUpdateTime(new Date());
        bizUserRecharge.setUpdateBy(SecurityUtils.getUsername());
        return bizUserRecharge.updateById();
    }

    /**
     * 批量删除用户充值
     *
     * @param ids 需要删除的用户充值主键
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean deleteBizUserRechargeByIds(Long[] ids) {
        return BizUserRecharge.DAO.delete(Wrappers.lambdaQuery(BizUserRecharge.class).in(BizUserRecharge::getId, (Object[]) ids));
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean changeStatus(BizStatusChangeVO vo) {
        //return BizUserRecharge.DAO.update(Wrappers.lambdaUpdate(BizUserRecharge.class).in(BizUserRecharge::getId, (Object[]) vo.getIds()).set(BizUserRecharge::getStatus, vo.getStatus()));
        return true;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Map<String, String> recharge(AppUserRechargeFormVO form) throws IOException {
        Map<String, String> payParams = new HashMap<>();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        BizUserRecharge recharge = new BizUserRecharge();
        recharge.setUserId(user.getUserId());
        recharge.setRechargeAmount(form.getRechargeAmount());
        recharge.setPaymentAmount(form.getPaymentAmount());
        recharge.setIsCustomize(form.getIsCustomize());
        recharge.setRechargeUnitId(form.getRechargeUnitId());
        String rechargeSerialNumber = redisCache.buildRechargeSerialNumber();
        recharge.setSerialNumber(rechargeSerialNumber);
        boolean insert = recharge.insert();
        if (insert) {
            //预生成支付流水
            BizUserRechargePayment payment = bizUserRechargePaymentService.createRechargePayment(rechargeSerialNumber, form, user.getUserId());
            if (StringUtils.equals(Constants.PAY_TYPE_WX_APPLET, form.getPayType())) {
                if ("".equals(form.getOpenId())){
                    try {
                        throw new Exception("微信小程序支付OpenId错误请重新获取");
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
                //调用统一下单API
                HttpPost httpPost = new HttpPost(wxPayConfig.getDomain().concat(WxApiType.JSAPI_PAY.getType()));
                AppServiceOrderVO appServiceOrderVO = bizServiceOrderService.getServiceOrderByOrderNum(form.getOrderNum());
                // 请求body参数
                Gson gson = new Gson();
                Map paramsMap = new HashMap();
                paramsMap.put("appid", wxPayConfig.getAppid());
                paramsMap.put("mchid", wxPayConfig.getMchId());
                paramsMap.put("description", appServiceOrderVO.getDispatchType());
                paramsMap.put("out_trade_no", appServiceOrderVO.getServiceOrderSn());
                paramsMap.put("notify_url", wxPayConfig.getNotifyDomain().concat("api/notify/payment/wxCallback"));
//                paramsMap.put("notify_url", wxPayConfig.getNotifyDomain().concat(WxNotifyType.NATIVE_NOTIFY.getType()));
                Map amountMap = new HashMap();
                BigDecimal amount = appServiceOrderVO.getAmount();
//                amountMap.put("total", amount.intValue()*100);
                // amountMap.put("total", 1);
                amountMap.put("currency", "CNY");
                paramsMap.put("amount", amountMap);
                Map payerMap = new HashMap();
                payerMap.put("openid",form.getOpenId());
                paramsMap.put("payer",payerMap);
                //将参数转换成json字符串
                String jsonParams = gson.toJson(paramsMap);
                log.info("请求参数 ===> {}" + jsonParams);

                StringEntity entity = new StringEntity(jsonParams,"utf-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
                httpPost.setHeader("Accept", "application/json");
                //完成签名并执行请求
                CloseableHttpResponse response = null;
                try {
                    response = wxPayClient.execute(httpPost);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                Map<String, String> prepay_id = new HashMap<>();
                try {
                    String bodyAsString = EntityUtils.toString(response.getEntity());//响应体
                    int statusCode = response.getStatusLine().getStatusCode();//响应状态码
                    if (statusCode == 200) { //处理成功
                        log.info("成功, 返回结果 = " + bodyAsString);
                        JSONObject jsonObject = JSON.parseObject(bodyAsString);
                        prepay_id = prepayIdCreateSign(jsonObject.get("prepay_id").toString());
                    } else if (statusCode == 204) { //处理成功，无返回Body
                        log.info("成功");
                    } else {
                        log.info("小程序微信支付失败,响应码 = " + statusCode+ ",返回结果 = " + bodyAsString);
                        throw new IOException("request failed");
                    }
                    //响应结果
                    Map<String, String> resultMap = gson.fromJson(bodyAsString, HashMap.class);
                    prepay_id.put("rechargeId", recharge.getId().toString());
                    String key = Constants.APPLET_WX_PAY_MAP + form.getOrderNum();
                    redisCache.setCacheMap(key,prepay_id);
                    log.info("下单成功:{}",prepay_id);
                    return prepay_id;
                } finally {
                    response.close();
                }
            }else if(StringUtils.equals(Constants.PAY_TYPE_WX, form.getPayType())){
                //微信支付
                WxPayApiConfig wxPayApiConfig = WxPayApiConfig.New()
                        .setAppId(appId)
                        .setMchId(mchId)
                        .setPaternerKey(secret);
                WxPayApiConfigKit.setThreadLocalWxPayApiConfig(wxPayApiConfig);
                String[] split = IpUtils.getIpAddr(ServletUtils.getRequest()).split(",");
                String ip = split[0];
                Map<String, String> params = WxPayApiConfigKit.getApiConfig(appId)
                        .setBody("陪护豆充值")
                        .setSpbillCreateIp(ip)
                        .setTotalFee(form.getPaymentAmount().multiply(BigDecimal.valueOf(100)).setScale(0).toString())
                        .setTradeType(WxPayApi.TradeType.APP)
                        .setNotifyUrl(notifyUrl + "/app/payment/callback")
                        .setOutTradeNo(payment.getId().toString())
                        .build();
                System.out.println("支付参数++++" + params);
                String xmlResult = WxPayApi.pushOrder(false, params);
                log.info(xmlResult);
                Map<String, String> resultMap = PaymentKit.xmlToMap(xmlResult);
                System.out.println("+++++++++++++" + resultMap);
                String prepayId = resultMap.get("prepay_id");
                payParams = prepayIdCreateSign(prepayId);
                payParams.put("rechargeId", recharge.getId().toString());
            } else if (StringUtils.equals(Constants.PAY_TYPE_ALIPAY, form.getPayType())) {
                //支付宝支付
                PayFactory payService = PayFactory.getPayService(PayMethodEnum.ALI_PAY);
                String s = payService.buildPayParams(payment.getRechargeSerialNumber(), payment.getPaymentAmount());
                payParams.put("aLiPayParams", s);
                payParams.put("rechargeId", recharge.getId().toString());
            }
        }
        System.out.println("构造支付参数====" + JSONObject.toJSONString(payParams) + "=======结束");
        return payParams;
    }

    @Override
    public AppPaymentStatusVO queryPayStatus(AppPaymentQueryPayStatusVO query) {
        AppPaymentStatusVO data = new AppPaymentStatusVO();
        BizUserRecharge recharge = BizUserRecharge.DAO.selectById(query.getRechargeId());
        if (StringUtils.isNotNull(recharge)) {
            //充值订单存在
            if (BizUserRecharge.PAY_STATUS_YES.equals(recharge.getPayStatus())) {
                data.setStatus(true);
            } else {
                data.setStatus(false);
            }
        }else {
            //充值订单不存在 就去查保证金订单
            BizUserEnsureMoney money = BizUserEnsureMoney.DAO.selectById(query.getRechargeId());
            if(StringUtils.isNull(money)){
                throw new ApiException("订单不存在");
            }
            if (BizUserEnsureMoney.PAID.equals(money.getPayStatus())) {
                data.setStatus(true);
            } else {
                data.setStatus(false);
            }
        }

        return data;
    }

    public Map<String, String> prepayIdCreateSign(String prepay_id) {
//        Map<String, String> packageParams = new HashMap<String, String>();
//        packageParams.put("appid", WxPayApiConfigKit.getWxPayApiConfig().getAppId());
//        packageParams.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
//        packageParams.put("noncestr", String.valueOf(System.currentTimeMillis()));
//        packageParams.put("package", "Sign=WXPay");
//        packageParams.put("partnerid", mchId);
//        packageParams.put("prepayid", prepay_id);
//        String packageSign = PaymentKit.createSign(packageParams,
//                WxPayApiConfigKit.getWxPayApiConfig().getPaternerKey());
//        packageParams.put("paySign", packageSign);
        Map<String, String> packageParams = new HashMap<String, String>();

        long l = System.currentTimeMillis();
        PayUtil payUtil = new PayUtil();
        String paySign = null;
        try {
            paySign = payUtil.getSign(wxPayConfig.getAppid(), l / 1000, String.valueOf(l), "prepay_id=" + prepay_id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        packageParams.put("paySign",paySign);
        packageParams.put("prepay_id",prepay_id);
        packageParams.put("nonceStr",l+"");
        packageParams.put("timeStamp",l/1000+"");
        return packageParams;
    }
}
